import {
  useCallback,
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
} from "react";
import "./index.scss";
import classNames from "classnames";
import { throttle } from "lodash";
import { useMouse } from "ahooks";

function GoodsImage({ images }: { images: any[] }) {
  const [currIndex, setCurrentIndex] = useState(0);
  const [show, setShow] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  const mouse = useMouse(ref.current);

  // 图片位置
  const [position, setPositon] = useState<{ left: number; top: number }>({
    left: 0,
    top: 0,
  });

  const [bgPosition, setBgPositon] = useState({
    backgroundPositionX: "",
    backgroundPositionY: "",
  });

  useEffect(() => {
    if (ref.current) {
      const { left, top, right, bottom } = ref.current.getBoundingClientRect();
      const isIn =
        mouse.clientX >= left &&
        mouse.clientX <= right &&
        mouse.clientY >= top &&
        mouse.clientY <= bottom;
      setShow(isIn);
    }
  }, [mouse]);

  // 包装 zks 函数，限制其执行频率
  const zks = useCallback(
    throttle(() => {
      if (!show) return;
      const newPosition = { left: 0, top: 0 };
      if (mouse.elementX < 100) {
        newPosition.left = 0;
      } else if (mouse.elementX > 300) {
        newPosition.left = 200;
      } else {
        newPosition.left = mouse.elementX - 100;
      }

      if (mouse.elementY < 100) {
        newPosition.top = 0;
      } else if (mouse.elementY > 300) {
        newPosition.top = 200;
      } else {
        newPosition.top = mouse.elementY - 100;
      }

      setPositon(newPosition);
      setBgPositon({
        backgroundPositionX: -newPosition.left * 2 + "px",
        backgroundPositionY: -newPosition.top * 2 + "px",
      });
    }, 16),
    [show, mouse]
  );

  useLayoutEffect(() => {
    zks();
  }, [zks, mouse]);

  return (
    <div className="goods-image">
      {show && (
        <div
          className="large"
          style={{
            backgroundImage: `url(${images[currIndex]})`,
            ...bgPosition,
          }}
        ></div>
      )}
      <div className="middle" ref={ref}>
        <img src={images[currIndex]} alt="" />
        {show && <div className="layer" style={position}></div>}
      </div>
      <ul className={classNames("small")}>
        {images.map((item, index) => (
          <li
            key={item}
            className={classNames({ active: currIndex === index })}
          >
            <img
              src={item}
              alt=""
              onMouseEnter={() => setCurrentIndex(index)}
            />
          </li>
        ))}
      </ul>
    </div>
  );
}

export default GoodsImage;
